package com.tuanzi.loan.business.service.statistics.impl;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.common.CommProductId;
import com.tuanzi.loan.business.repository.statistics.ActivityAverageJoinStatRepository;
import com.tuanzi.loan.business.repository.statistics.ActivityParticipateStatRepository;
import com.tuanzi.loan.business.repository.statistics.DayActivityProdChannelStatRepository;
import com.tuanzi.loan.business.service.statistics.ActivityAverageJoinStatService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.statistics.ActivityAverageJoinStatRequest;
import com.tuanzi.loan.vo.response.statistics.ActivityAverageJoinStatResponse;
import com.tuanzi.server.loan_base.model.db.CommProductPrdid;
import org.apache.commons.lang.StringUtils;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Debug
@Service
@Transactional
@Retryable(value = { RetryException.class })
public class ActivityAverageJoinStatServiceImpl implements ActivityAverageJoinStatService{
	
	@Autowired
	private ActivityAverageJoinStatRepository activityAverageJoinStatRepository;
	
	@Autowired
	private ActivityParticipateStatRepository activityParticipateStatRepository;
	
	@Autowired
	private DayActivityProdChannelStatRepository dayActivityProdChannelStatRepository;
	
	private DecimalFormat decimalFormat1 = new DecimalFormat("#.##%");
	private DecimalFormat decimalFormat2 = new DecimalFormat("0.00");
	
	/**
	 * 将选中产品的树形结构转换为list
	 * @param searchRequest
	 * @return
	 */
	private List<Integer> getProdList(ActivityAverageJoinStatRequest searchRequest) {
		TreeNode[] nodes = searchRequest.getProdNodes();
		if(nodes == null || nodes.length == 0) {
			return null;
		}
		
		List<Integer> selectedProdList = Lists.newArrayList();
		for(TreeNode node : nodes) {
			CommProductPrdid prod = (CommProductPrdid) node.getData();
			if(prod.getLevel() == 2) {
				selectedProdList.add(prod.getPrdid());
			}
		}
		return selectedProdList;
	}
	

	
	public Page<ActivityAverageJoinStatResponse> list(PageSearcher<ActivityAverageJoinStatRequest> pageSearcher) {
		ActivityAverageJoinStatRequest searchCondition = pageSearcher.getSearchCondition();
		TreeNode[] prodNodes = searchCondition.getProdNodes();
		List<Integer> productList = new ArrayList<>();
		List<String> parentIdList = new ArrayList<>();
		if(null != prodNodes && prodNodes.length >0){
			for (TreeNode productNode : prodNodes) {
				CommProductId data = (CommProductId) productNode.getData();
				Integer productId = data.getProductId();
				if(null != productId){
					productList.add(productId);
					String parentId = data.getParentId();
					if(StringUtils.isNotBlank(parentId) && -1000 == productId){
						parentIdList.add(parentId);
					}
				}
			}
		}
		searchCondition.setParentIdList(parentIdList);
		searchCondition.setProductId(productList);

		// 参与统计
		Page<ActivityAverageJoinStatResponse> activityJoinListPage = activityParticipateStatRepository
				.getlistPageByActivityJoin(searchCondition, pageSearcher.getPageable());
		// 日活统计
		Page<ActivityAverageJoinStatResponse> activeListPage = activityAverageJoinStatRepository
				.getListByAverageJoin(searchCondition);
		
		handleData(activityJoinListPage, activeListPage);
		
		return activityJoinListPage;
	}
	
	private void handleData(Page<ActivityAverageJoinStatResponse> activityJoinListPage,
			Page<ActivityAverageJoinStatResponse> activeListPage) {
		Map<String, Integer> activeMap = new HashMap<String, Integer>();
		List<ActivityAverageJoinStatResponse> activeList = activeListPage.getContent();
		if(activeList != null) {
			for(ActivityAverageJoinStatResponse active : activeList) {
				//兼容平台为iphone的情况
				String platform = active.getPlatform();
				if(StringUtils.isNotBlank(platform) && "iphone".equalsIgnoreCase(platform)){
					active.setPlatform("ios");
				}
				activeMap.put(active.getDate()+"_"+active.getProductId()+"_"+active.getParentId()+"_"+active.getUserType()+"_"+active.getPlatform(), active.getActivity_uv());
			}
		}
		
		Map<String, String> prodMap = activityParticipateStatRepository.getProdMap();
		List<ActivityAverageJoinStatResponse> joinList = activityJoinListPage.getContent();
		if(joinList != null) {
			
			for(ActivityAverageJoinStatResponse join : joinList) {
				String key = join.getDate()+"_"+join.getProductId()+"_"+join.getParentId()+"_"+join.getUserType()+"_"+join.getPlatform();
				Integer activeUv = activeMap.get(key);
				if(activeUv != null && activeUv != 0) {
					if(join.getShow_uv() != null) {
						String perShowAct = decimalFormat2.format(join.getShow_uv().doubleValue() / activeUv.doubleValue());
						join.setPer_show_act(perShowAct);
					}
					if(join.getClick_uv() != null) {
						String perClickAct = decimalFormat2.format(join.getClick_uv().doubleValue() / activeUv.doubleValue());
						join.setPer_click_act(perClickAct);
					}
				}
				if(join.getShow_uv()!=null && join.getShow_uv() != 0 && join.getClick_uv() != null) {
					String perClickShow = decimalFormat1.format(join.getClick_uv().doubleValue() / join.getShow_uv().doubleValue());
					join.setPer_click_show(perClickShow);
				}
				join.setActivity_uv(activeUv);
				
				String prodName = prodMap.get(join.getProductId());
				join.setProductName(prodName);
				
				if("1".equals(join.getUserType())) {
					join.setUserType("新用户");
				} else if("0".equals(join.getUserType())) {
					join.setUserType("老用户");
				} else if("-1000".equals(join.getUserType())) {
					join.setUserType("全部");
				}
				
				if("-1000".equals(join.getPlatform())) {
					join.setPlatform("全部");
				}
				
				if("-1000".equals(join.getAdId())) {
					join.setAdId("全部");
				}
			}
		}
	}
	
	public String getExcelOfProdChannel(ActivityAverageJoinStatRequest searchRequest) {
		searchRequest.setProductId(getProdList(searchRequest));
		// 参与统计
		Page<ActivityAverageJoinStatResponse> activityJoinListPage = activityParticipateStatRepository
					.getAllListOfProdChannel(searchRequest);
		// 日活统计
		Page<ActivityAverageJoinStatResponse> activeListPage = dayActivityProdChannelStatRepository
					.getList(searchRequest);
		
		handleDataOfProdChannel(activityJoinListPage,activeListPage);
		
    	List<ActivityAverageJoinStatResponse> list = activityJoinListPage.getContent();
    	StringBuffer sf = new StringBuffer();
		sf.append("时间,产品,渠道,用户类型,平台,广告ID,活跃,页面UV,曝光UV,详情UV,参与UV,人均详情,人均参与,参与/详情\r\n");
		if(list != null) {
			for(ActivityAverageJoinStatResponse response : list) {
				sf.append(response.getDate()+",");
				sf.append(response.getProductName()+",");
				sf.append(response.getChannelName()+",");
				sf.append(response.getUserType()+",");
				sf.append(response.getPlatform()+",");
				sf.append(response.getAdId()+",");
				sf.append(response.getActivity_uv()+",");
				sf.append(response.getPage_uv()+",");
				sf.append(response.getExposure_uv()+",");
				sf.append(response.getShow_uv()+",");
				sf.append(response.getClick_uv()+",");
				sf.append(response.getPer_show_act()+",");
				sf.append(response.getPer_click_act()+",");
				sf.append(response.getPer_click_show());
				sf.append("\r\n");
			}
		}
    	
    	return sf.toString();
    }
	
	/**
	 * 产品渠道
	 */
	public Page<ActivityAverageJoinStatResponse> listProdChannel(PageSearcher<ActivityAverageJoinStatRequest> pageSearcher) {
		pageSearcher.getSearchCondition().setProductId(getProdList(pageSearcher.getSearchCondition()));
		// 参与统计
		Page<ActivityAverageJoinStatResponse> activityJoinListPage = activityParticipateStatRepository
				.getlistPageByActivityJoinOfProdChannel(pageSearcher.getSearchCondition(), pageSearcher.getPageable());
		// 日活统计
		Page<ActivityAverageJoinStatResponse> activeListPage = dayActivityProdChannelStatRepository
				.getList(pageSearcher.getSearchCondition());
		
		handleDataOfProdChannel(activityJoinListPage, activeListPage);
		
		return activityJoinListPage;
	}
	
	// **
	private void handleDataOfProdChannel(Page<ActivityAverageJoinStatResponse> activityJoinListPage,
			Page<ActivityAverageJoinStatResponse> activeListPage) {
		Map<String, Integer> activeMap = new HashMap<String, Integer>();
		List<ActivityAverageJoinStatResponse> activeList = activeListPage.getContent();
		if(activeList != null) {
			for(ActivityAverageJoinStatResponse active : activeList) {
				activeMap.put(active.getDate()+"_"+active.getProductId()+"_"+active.getUserType()+"_"+active.getChannelId(), active.getActivity_uv());
			}
		}
		
		Map<String, String> prodMap = activityParticipateStatRepository.getProdMap();
		Map<String, String> channelMap = activityParticipateStatRepository.getChannelMap();
		List<ActivityAverageJoinStatResponse> joinList = activityJoinListPage.getContent();
		if(joinList != null) {
			for(ActivityAverageJoinStatResponse join : joinList) {
				String key = join.getDate()+"_"+join.getProductId()+"_"+join.getUserType()+"_"+join.getChannelId();
				Integer activeUv = activeMap.get(key);
				if(activeUv != null && activeUv != 0) {
					if(join.getShow_uv() != null) {
						String perShowAct = decimalFormat2.format(join.getShow_uv().doubleValue() / activeUv.doubleValue());
						join.setPer_show_act(perShowAct);
					}
					if(join.getClick_uv() != null) {
						String perClickAct = decimalFormat2.format(join.getClick_uv().doubleValue() / activeUv.doubleValue());
						join.setPer_click_act(perClickAct);
					}
				}
				if(join.getShow_uv()!=null && join.getShow_uv() != 0 && join.getClick_uv() != null) {
					String perClickShow = decimalFormat1.format(join.getClick_uv().doubleValue() / join.getShow_uv().doubleValue());
					join.setPer_click_show(perClickShow);
				}
				join.setActivity_uv(activeUv);
				
				String prodName = prodMap.get(join.getProductId());
				String channelName = channelMap.get(join.getChannelId());
				join.setProductName(prodName);
				join.setChannelName(channelName);
				
				if("1".equals(join.getUserType())) {
					join.setUserType("新用户");
				} else if("0".equals(join.getUserType())) {
					join.setUserType("老用户");
				} else if("-1000".equals(join.getUserType())) {
					join.setUserType("全部");
				}
				
				if("-1000".equals(join.getPlatform())) {
					join.setPlatform("全部");
				}
				
				if("-1000".equals(join.getAdId())) {
					join.setAdId("全部");
				}
			}
		}
	}
	
}

























